var cusIds = [];
var comSts = "";

function addCustomer() {
	// 获取焦点显示
	// $("#cusIds").focus(function () {
	// 	$(".pdmiddle").show();
	// });
	// this.pdclose = function () {
	// 	// $('#gridContainer_2_2_3').removeClass('n-pt-15');
	// 	$(".pdmiddle").hide();
	// };

	$(".cSubmit").on('click', function () {
		var cids = "";

		for (var i = 0; i < customerArry.length; i++) {
			if (i == 0) {
				cids = customerArry[0];
			} else {
				cids += "," + customerArry[i];
			}
		}
		if (cids == "" || cids == null || cids == undefined) {
			layer.msg("请至少选择一个客户进行关联！");
			return;
		}

		$certusUtils.ajax("addProCus", {
			"projId": proId,
			"cusIds": cids
		}, function () {
			layer.msg("提交成功");
			toLoadHtml(5);
		})
	})
}
$(".btn-info11111").on('click', function () {
	$('#gridContainer_2_2_3').addClass('n-pt-15');
	var customerColumns = [{
		id: 'com_name',
		title: '客户名称',
		type: 'string',
		width: 100,
		columnClass: 'text-center'
	},
	{
		id: 'com_type',
		title: '客户类型',
		type: 'string',
		width: 75,
		columnClass: 'text-center'
	},
	{
		id: 'industry',
		title: '行业',
		type: 'string',
		columnClass: 'text-center'
	},
	{
		id: 'userId',
		title: '我司负责人',
		type: 'string',
		width: 100,
		columnClass: 'text-center'
	},
	{
		id: 'operation',
		title: '操作',
		type: 'string',
		width: 60,
		columnClass: 'text-center',
		resolution: function (value, record) {
			var content = '';
			var flag = false;
			for (var i = 0; i < cusIds.length; i++) {
				if (record.id == cusIds[i]) {
					flag = true;
				}
			}
			if (flag) {
				//选中
				content += '<span id="cus' + record.id + '"><input type="button" value="取消" class="btn btn-xs btn-success"  onclick="delsu(' + record.id + ',\'' + record.com_name + '\');"></span>';
			} else {
				content += '<span id="cus' + record.id + '"><input type="button" value="选择" class="btn btn-xs btn-success" onclick="selsu(' + record.id + ',\'' + record.com_name + '\');"></span>';
			}
			return content;
		}
	}
	];
	$("#gridContainer_2_2_3").empty();
	$("#gridToolBarContainer_2_2_3").empty();
	$CertusJsonAjax.dataInit("findList", {
		"code": "1",
		"param": $("#cusName").val(),
		"userId": "0"
	}, customerColumns,
		"gridContainer_2_2_3", "gridToolBarContainer_2_2_3");

});

function selsu(cusId, comName) {
	$("#cus" + cusId).html('<input type="button" value="取消" class="btn btn-xs btn-success" onclick="delsu(' + cusId + ',\'' + comName + '\')"/>');
	if (comSts == "") {
		comSts += comName;
	} else {
		comSts += "," + comName;
	}
	cusIds.push(cusId);
	$("#cusIds").val(comSts);
}

function delsu(cusId, comName) {
	$("#cus" + cusId).html('<input type="button" value="选择" class="btn btn-xs btn-success" onclick="selsu(' + cusId + ',\'' + comName + '\')"/>');
	if (comSts != "") {
		comSts = comSts.replace("," + comName, "");
	}
	cusIds.splice($.inArray(cusId, cusIds), 1);
	$("#cusIds").val(comSts);
}

//拜访记录
function findVisit() {
	// 客户拜访记录管理数据
	var ctlogColumns = [{
		id: 'visit_time',
		title: '拜访日期',
		width: 100,
		type: 'date',
		format: 'yyyy-MM-dd',
		otype: 'time_stamp_ms',
		columnClass: 'text-center'
	}, {
		id: 'com_name',
		title: '客户公司',
		width: 150,
		type: 'string',
		columnClass: 'text-center'
	},
	{
		id: 'customer_name',
		title: '客户名称',
		width: 150,
		type: 'string',
		columnClass: 'text-center'
	},
	{
		id: 'user_name',
		title: '拜访人',
		width: 75,
		type: 'string',
		columnClass: 'text-center'
	},
	{
		id: 'content',
		title: '具体内容',
		type: 'string',
		columnClass: 'text-left'
	},
	{
		id: 'operation',
		title: '操作',
		type: 'string',
		width: 130,
		columnClass: 'text-center',
		resolution: function (value, record) {
			var content = '';
			//计算相差多少天
			var fordate = new Date(record.create_time);
			var nfordate = $.fn.dlshouwen.grid.tools.dateFormat(fordate, "yyyy-MM-dd");

			var d = new Date();
			var start = nfordate.replace(/-/g, "/");
			var startdate = new Date(start);
			var time = d.getTime() - startdate.getTime();
			var days = parseInt(time / (1000 * 60 * 60 * 24));
			//大于三天则不能修改和删除
			if (days <= 3) {
				content += '<button class="btn btn-xs btn-info" onclick="editCtlog(' + record.id + ');"><i class="fa fa-edit"></i>  编辑</button>';
				content += '  ';
				content += '<button class="btn btn-xs btn-danger" onclick="delCtlog(' + record.id + ');"><i class="fa fa-trash-o"></i>  删除</button>';
			}
			return content;
		}
	}
	];
	$certusUtils.ajax("findProVisitList", {
		"projId": proId
	}, function (res) {
		var ctlogOption = {
			lang: 'zh-cn',
			ajaxLoad: false,
			extraWidth: 20,
			// loadURL:'url',
			exportFileName: '客户拜访记录',
			datas: res.data,
			columns: ctlogColumns,
			gridContainer: 'ctlogContainer',
			toolbarContainer: 'ctlogToolBarContainer',
			tools: '',
			pageSize: 10,
			pageSizeLimit: [10, 15, 20]
		};
		var ctlogGrid = $.fn.dlshouwen.grid.init(ctlogOption);
		ctlogGrid.load();
	});
}

function addVisit() {
	$certusUtils.ajax("findCompOName", {}, function (response) {
		var data = response.data;
		for (var i = 0; i < data.length; i++) {
			$("#comId").append("<option value='" + data[i].id + "'>" + data[i].comName + "</option>");
		}
	});
	//项目成员
	$certusUtils.ajax("findMemberList", {
		"proId": proId
	}, function (response) {
		var data = response.data;
		for (var i = 0; i < data.length; i++) {
			$("#userId").append("<option value='" + data[i].userId + "'>" + data[i].userName + "</option>");
		}
	});
	// $certusUtils.ajax("findSpUserList",{},function (response) {
	//     var nhlTeams = [];
	//     var data = response.data;
	//     for (var i=0;i<data.length;i++){
	//         var arr={};
	//         arr.name=data[i].userName;
	//         arr.id = data[i].userId;
	//         nhlTeams.push(arr);
	//     }
	//     //自动补全
	//     var nhl = $.map(nhlTeams, function (obj) {
	//         return {
	//             value: obj.name,
	//             data: { category: obj.id }
	//         };
	//     });
	//     // Initialize autocomplete with local lookup:
	//     $('#autocomplete').devbridgeAutocomplete({
	//         lookup: nhl,
	//         minChars: 1,
	//         onSelect: function (suggestion) {
	//             $("#userId").val(suggestion.data.category);
	//         },
	//         showNoSuggestionNotice: true,
	//         noSuggestionNotice: 'Sorry, no matching results'
	//     });
	// });
	$(".vsubmit").on('click', function () {
		if ($("#comId").val() == "" || $("#comId").val() == null || $("#comId").val() == undefined) {
			layer.msg("客户公司名称不能为空!");
			return;
		}

		if ($("#cusName").val() == "" || $("#cusName").val() == null || $("#cusName").val() == undefined) {
			layer.msg("客户人员名称不能为空!");
			return;
		}
		if ($("#time").val() == "" || $("#time").val() == null || $("#time").val() == undefined) {
			layer.msg("拜访时间不能为空!");
			return;
		}
		if ($("#userId").val() == "" || $("#userId").val() == null || $("#userId").val() == undefined) {
			layer.msg("拜访人不能为空!");
			return;
		}
		if ($("#content").val() == "" || $("#content").val() == null || $("#content").val() == undefined) {
			layer.msg("拜访内容不能为空!");
			return;
		}
		var arr = $("form").serializeArray();
		var data = {};
		for (var i = 0; i < arr.length; i++) {
			data[arr[i].name] = arr[i].value;
		};
		data.proId = proId;
		data.visitTime = $("#time").val();
		$certusUtils.ajax("addVisit", {
			"params": JSON.stringify(data)
		}, function () {
			layer.msg("添加成功！");
			toLoadHtml(24);
		})
	})
}


// 选择关联客户-客户自动补全
$certusUtils.ajax("findComList", {}, function (response) {
	var nhlTeams = [];
	var data = response.data;
	for (var i = 0; i < data.length; i++) {
		var arr = {};
		arr.name = data[i].comName + "（" + data[i].comShortName + "）-----" + data[i].userName;
		arr.id = data[i].id;
		nhlTeams.push(arr);
	}
	//自动补全
	var nhl = $.map(nhlTeams, function (obj) {
		return {
			value: obj.name,
			data: { category: obj.id }
		};
	});
	$('#cusName').devbridgeAutocomplete({
		lookup: nhl,
		minChars: 1,
		onSelect: function (suggestion) {
			$("#cusId").val(suggestion.data.category);
			// var cusName = $("#customerName").val().split("-----");
			// customerSearch(suggestion.data.category);
			// customerClean();
			// console.log(customerArry)
		},
		showNoSuggestionNotice: true,
		noSuggestionNotice: 'Sorry, no matching results'
	});
});


function toBack(uflag, t) {
	toLoadHtml(uflag, t);
}

function editCtlog(id) {
	toLoadHtml(21, id);
}

function editVisit(id) {
	$certusUtils.ajax("findCompOName", {}, function (response) {
		var data = response.data;
		for (var i = 0; i < data.length; i++) {
			$("#comId").append("<option value='" + data[i].id + "'>" + data[i].comName + "</option>");
		}

		$certusUtils.ajax("findvisitInfo", {
			"id": id
		}, function (response) {
			var data = response.data;
			var date = new Date(data.visitTime);
			var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd");
			$("#time").val(content);
			$("#cusName").val(data.customerName);
			$("#content").val(data.content);
			$("#userId").val(data.userId);
			$("#comId").val(data.comId);
		});
	});
	// $certusUtils.ajax("findSpUserList",{},function (response) {
	//     var nhlTeams = [];
	//     var data = response.data;
	//     for (var i=0;i<data.length;i++){
	//         var arr={};
	//         arr.name=data[i].userName;
	//         arr.id = data[i].userId;
	//         nhlTeams.push(arr);
	//     }
	//     //自动补全
	//     var nhl = $.map(nhlTeams, function (obj) {
	//         return {
	//             value: obj.name,
	//             data: { category: obj.id }
	//         };
	//     });
	//     // Initialize autocomplete with local lookup:
	//     $('#autocomplete').devbridgeAutocomplete({
	//         lookup: nhl,
	//         minChars: 1,
	//         onSelect: function (suggestion) {
	//             $("#userId").val(suggestion.data.category);
	//         },
	//         showNoSuggestionNotice: true,
	//         noSuggestionNotice: 'Sorry, no matching results'
	//     });
	// });
	//项目成员
	$certusUtils.ajax("findMemberList", {
		"proId": proId
	}, function (response) {
		var data = response.data;
		for (var i = 0; i < data.length; i++) {
			$("#userId").append("<option value='" + data[i].userId + "'>" + data[i].userName + "</option>");
		}
	});


	$(".vsubmit").on('click', function () {
        if ($("#comId").val() == "" || $("#comId").val() == null || $("#comId").val() == undefined) {
            layer.msg("客户公司名称不能为空!");
            return;
        }

        if ($("#cusName").val() == "" || $("#cusName").val() == null || $("#cusName").val() == undefined) {
            layer.msg("客户人员名称不能为空!");
            return;
        }
        if ($("#time").val() == "" || $("#time").val() == null || $("#time").val() == undefined) {
            layer.msg("拜访时间不能为空!");
            return;
        }
        if ($("#userId").val() == "" || $("#userId").val() == null || $("#userId").val() == undefined) {
            layer.msg("拜访人不能为空!");
            return;
        }
        if ($("#content").val() == "" || $("#content").val() == null || $("#content").val() == undefined) {
            layer.msg("拜访内容不能为空!");
            return;
        }

		var arr = $("form").serializeArray();
		var data = {};
		for (var i = 0; i < arr.length; i++) {
			data[arr[i].name] = arr[i].value;
		};
		data.id = id;
		$certusUtils.ajax("editVisit", {
			"params": JSON.stringify(data)
		}, function () {
            toLoadHtml(24);
		})
	})
}

function delCtlog(id) {
	layer.confirm('确认删除此数据？', {
		btn: ['确认', '取消'] //按钮
	}, function () {
		$certusUtils.ajax("delVisit", {
			"id": id
		}, function () {
			toLoadHtml(24);
		})
		layer.msg("删除成功");
	})
}



// 优化选择关联客户
// 选择关联客户-客户自动补全
$certusUtils.ajax("findComList", {}, function (response) {
	var nhlTeams = [];
	var data = response.data;
	for (var i = 0; i < data.length; i++) {
		var arr = {};
		arr.name = data[i].comName + "（" + data[i].comShortName + "）-----" + data[i].userName;
		arr.id = data[i].id;
		arr.comUser = data[i];
		nhlTeams.push(arr);
	}
	//自动补全
	var nhl = $.map(nhlTeams, function (obj) {
		return {
			value: obj.name,
			data: obj
		};
	});
	$('#customerName').devbridgeAutocomplete({
		lookup: nhl,
		minChars: 1,
		onSelect: function (suggestion) {
			$("#customerId").val(suggestion.data.id);
			customerSearch(suggestion.data);
			customerClean();
		},
		showNoSuggestionNotice: true,
		noSuggestionNotice: 'Sorry, no matching results'
	});
});

// 客户组
var customerArry = [];

// 选择关联客户-添加检测重复数据
function customerSearch(userArr) {
	var comUser = userArr.comUser;
	var id = userArr.id;
	if (customerArry.indexOf(id) > -1) {
		layer.msg("已存在，请勿重复添加！")
		return
	} else {
		customerArry.push(id);
		$("#customerList").append(
			`<tr id="` + id + `" style="text-align:center;">
				<td>`+comUser.comName+`</td>
				<td>`+comUser.industry+`</td>
				<td>`+comUser.comType+`</td>
				<td>`+comUser.userName+`</td>
				<td>
				<button class="btn btn-xs btn-danger" onclick="customerDel(`+ id + `)">
					<i class="fa fa-trash-o"></i> 删除
				</button>
				</td>
			</tr>`
		);
	}
}

// 客户组删除
function removeArry(arr, val) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] == val) {
			arr.splice(i, 1);
			break;
		}
	}
}

// 选择关联客户-删除操作
function customerDel(id) {
	layer.confirm('确认删除此数据？', {
		btn: ['确认', '取消'] //按钮
	}, function () {
		if (customerArry.length === 1) {
			layer.msg('请至少保留一个关联客户！');
			return
		} else {
			$("#" + id).remove();
			removeArry(customerArry, id);
			layer.msg("删除成功");
		}

	});
}

// 选择关联客户-清空操作
function customerClean() {
	$("#customerName").val("");
	$("#customerId").val("");
}